package com.cn.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.cn.gmall.common.constant.RedisConst;
import com.cn.gmall.common.result.Result;
import com.cn.gmall.common.util.IpUtil;
import com.cn.gmall.model.user.UserInfo;
import com.cn.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@ResponseBody
@SuppressWarnings("all")
@RequestMapping("/api/user/passport")
public class LongInApiController {

    @Autowired
    private UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 退出
     * 清空cookie 和redis
     * @return
     */

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
//        删除redis里面的存储的数据
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));


        return  Result.ok();
    }

    /***
     * 登录
     * /api/user/passport/login
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        UserInfo user = userService.longIn(userInfo);
        if (!ObjectUtils.isEmpty(user)) {
//      生产token
            String token = UUID.randomUUID().toString().replaceAll("-", "");
//        将数据存在redis
            String ipAddress = IpUtil.getIpAddress(request);//获取请求的requestip地址
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ip", ipAddress);
            jsonObject.put("userId", user.getId());

//        将数据存在redis          user:login:token
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token, jsonObject.toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            Map<String, String> resultMap = new HashMap<>();

            resultMap.put("token", token);
            resultMap.put("nickName", user.getNickName());

            return Result.ok(resultMap);
        } else {
            return Result.fail().message("用户名或密码错误!");
        }
    }

}
